#include <iostream>
#include <pthread.h>
#include <unistd.h>
using namespace std;

#define BUFFER_SIZE 5

pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t p_cond = PTHREAD_COND_INITIALIZER;
pthread_cond_t c_cond = PTHREAD_COND_INITIALIZER;

int buffer[BUFFER_SIZE];
int in = 0; // 生产者插入位置
int out = 0; // 消费者插入位置

int Data = 0;

void* producer(void* arg)
{
    while (1)
    {
        pthread_mutex_lock(&mutex);
        while ((in + 1) % BUFFER_SIZE == out) // 缓冲区满
        {
            pthread_cond_wait(&p_cond, &mutex);
        }
        cout << "producer: " << Data << endl;
        buffer[in++] = Data++;
        in %= BUFFER_SIZE;
        pthread_cond_signal(&c_cond);
        pthread_mutex_unlock(&mutex);
    }
    return nullptr;
}

void* consumer(void* arg)
{
    int t = 0;
    while (1)
    {
        pthread_mutex_lock(&mutex);
        while (in == out)
        {
            pthread_cond_wait(&c_cond, &mutex);
        }
        t = buffer[out++];
        out %= BUFFER_SIZE;
        cout << "comsumer: " << t << endl;
        sleep(1);
        pthread_cond_signal(&p_cond); 
        pthread_mutex_unlock(&mutex);
    }
    return nullptr;
}

int main()
{
    pthread_t producer_thread, consumer_thread;
    pthread_create(&producer_thread, nullptr, producer, nullptr);
    pthread_create(&consumer_thread, nullptr, consumer, nullptr);

    pthread_join(producer_thread, nullptr);
    pthread_join(consumer_thread, nullptr);

    pthread_mutex_destroy(&mutex);
    pthread_cond_destroy(&p_cond);
    pthread_cond_destroy(&c_cond);

    return 0;
}